﻿using System;
using System.Collections.Generic;

namespace smp.RabbitMq
{
    public class SubscriberHandlers
    {
        private readonly Dictionary<string, List<ISubscriberHandler>> _messageHandlers = new Dictionary<string, List<ISubscriberHandler>>();

        internal List<ISubscriberHandler> GetHandlers(string messageType)
        {
            if (!_messageHandlers.ContainsKey(messageType))
                return new List<ISubscriberHandler>();
            return _messageHandlers[messageType];
        }

        public SubscriberHandlers Add<TMessage>(ISubscriberHandler<TMessage> handler)
        {
            var messageType = typeof (TMessage).AssemblyQualifiedName;
            if(messageType == null)
                throw new Exception("Invalid ISubscriberHandler instance, TMessage must have a AssemblyQualifiedName")
                    ;
            if (!_messageHandlers.ContainsKey(messageType))
            {
                _messageHandlers.Add(messageType, new List<ISubscriberHandler>());
            }
            _messageHandlers[messageType].Add(handler);
            return this;
        }
    }

    public class ResponderHandlers
    {
        private readonly Dictionary<string, IResponderHandler> _messageHandlers = new Dictionary<string, IResponderHandler>();

        internal IResponderHandler GetHandler(string messageType)
        {
            if (!_messageHandlers.ContainsKey(messageType))
                return null;
            return _messageHandlers[messageType];
        }

        public ResponderHandlers Add<TMessage, TResponse>(IResponderHandler<TMessage, TResponse> handler)
        {
            var messageType = typeof(TMessage).AssemblyQualifiedName;
            if (messageType == null)
                throw new Exception("Invalid ISubscriberHandler instance, TMessage must have a AssemblyQualifiedName")
                    ;
            if (_messageHandlers.ContainsKey(messageType))
            {
                throw new Exception("Cannot host two responders for the same message.");
            }

            _messageHandlers.Add(messageType, handler);
            return this;
        }
    }
}
